import yaml

from pyparsing import delimitedList, Keyword, Literal, oneOf
from base import Base
import helper as hp

ltrl = lambda value: Literal(value).suppress()

class PrefixList(Base):
    def __init__(self):
        self._pfl = []

    @hp.addlinenumber
    def _addStdPrefixList(self, string, location, tokens):
        pfl = {}
        pfl["name"] = tokens[0]
        pfl["ip"] = tokens[1:]
        self._pfl.append(pfl)

    @hp.addlinenumber
    def _addPrefixList(self, string, location, tokens):
        pfl = {}
        pfl["name"] = tokens[0]
        if tokens[1] == "plain":
            iplist = []
            with open(tokens[-1], "r") as fh:
                for line in fh.readlines():
                    iplist.append(line.strip())

            pfl["ip"] = iplist

        self._pfl.append(pfl)


    @hp.addlinenumber
    def _addYamlPrefixList(self, string, location, tokens):
        print(tokens)

    @property
    def grammar(self):
        pfxfileopt = oneOf("yaml plain")
        prefixlist = delimitedList(hp.ipaddr | hp.ip6addr)
        stdpfxopt = (hp.identifier + hp.lb + prefixlist +
                hp.rb).setParseAction(self._addStdPrefixList)
        pfxopt = (hp.identifier + hp.lt + pfxfileopt +
                hp.filename).setParseAction(self._addPrefixList)
        ymlpfxopt = (hp.lt + ltrl("yaml") + hp.filename).setParseAction(
                self._addYamlPrefixList)

        prefixopts = (stdpfxopt | pfxopt | ymlpfxopt)
        return Keyword("prefix-list") + prefixopts

    @property
    def value(self):
        return self._pfl
